<template>
  <div class="test-arrange">
    <div class="left">
      <div class="top">
        <div class="fc-toolbar">
          <div class="fc-left">
            <!-- <el-button class="arrange-btn" size="mini" @click="today">
              今天
            </el-button> -->
            <el-button class="arrange-btn" size="mini" @click="toNowMonth">
              本月
            </el-button>
          </div>
          <div class="fc-center">
            <el-button
              class="arrange-btn"
              size="mini"
              icon="el-icon-arrow-left"
              @click="prev"
            />
            <div class="title">
              {{ title }}
            </div>
            <el-button
              class="arrange-btn"
              size="mini"
              icon="el-icon-arrow-right"
              @click="next"
            />
          </div>
          <div class="fc-right">
            <el-button-group>
              <!-- <el-button class="arrange-btn" size="mini" @click="month">
                月
              </el-button>
              <el-button class="arrange-btn" size="mini" @click="week">
                周
              </el-button> -->
            </el-button-group>
          </div>
        </div>
        <div v-loading="loading">
          <FullCalendar
            id="calendar"
            ref="fullCalendar"
            class="demo-app-calendar"
            :options="calendarOptions"
          >
          </FullCalendar>
        </div>
      </div>
      <div class="bottom">
        <gantt-chart
          :infoDateStr="infoDateStr"
          @handleDragTime="handleDragTime"
        ></gantt-chart>
      </div>
    </div>
    <div class="right">
      <!-- 搜索 -->
      <div class="right-tools">
        <el-input placeholder="请输入内容" v-model="dataSetName">
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-button class="arrange-btn" size="mini" @click="searchList"
          >搜索</el-button
        >
      </div>
      <div class="right-content">
        <!-- 话音 -->
        <div class="list-wrap">
          <div class="title voice">
            <img
              :src="require('@/assets/images/taskArrangement/voice.png')"
              class="title-img"
            />
            <div class="title-name">话音</div>
          </div>
          <div class="content">
            <div
              class="content-item"
              v-for="(item, index) in dataSetListData[1]"
              :key="index"
              draggable="true"
              @click="showDialog(item, 1)"
              @dragstart="handleDragStart($event, 1, '任务定义',item)"
            >
              <div class="text">
                <img
                  :src="require('@/assets/images/taskArrangement/voice.png')"
                />
                <span>{{ item.dataSetName }}</span>
              </div>
              <div class="time">
                <div>文件时长：</div>
                <div>{{ item.estimatedTransmissionDuration }}</div>
              </div>
              <div class="size">
                <div>文件大小：</div>
                <div>{{ item.fileSize }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 数据 -->
        <div class="list-wrap">
          <div class="title data">
            <img
              :src="require('@/assets/images/taskArrangement/data.png')"
              class="title-img"
            />
            <div class="title-name">数据</div>
          </div>
          <div class="content">
            <div
              class="content-item"
              v-for="(item, index) in dataSetListData[2]"
              :key="index"
              draggable="true"
              @click="showDialog(item, 2)"
              @dragstart="handleDragStart($event, 2, '任务定义',item)"
            >
              <div class="text">
                <img
                  :src="require('@/assets/images/taskArrangement/data.png')"
                />
                <span>{{ item.dataSetName }}</span>
              </div>
              <div class="time">
                <div>文件时长：</div>
                <div>{{ item.estimatedTransmissionDuration }}</div>
              </div>
              <div class="size">
                <div>文件大小：</div>
                <div>{{ item.fileSize }}</div>
              </div>
            </div>
          </div>
        </div>
        <!-- 视频 -->
        <div class="list-wrap">
          <div class="title vedio">
            <img
              :src="require('@/assets/images/taskArrangement/vedio.png')"
              class="title-img"
            />
            <div class="title-name">视频</div>
          </div>
          <div class="content">
            <div
              class="content-item"
              v-for="(item, index) in dataSetListData[3]"
              :key="index"
              @click="showDialog(item, 3)"
              draggable="true"
              @dragstart="handleDragStart($event, 3, '任务定义',item)"
            >
              <div class="text">
                <img
                  :src="require('@/assets/images/taskArrangement/vedio.png')"
                />
                <span>{{ item.dataSetName }}</span>
              </div>
              <div class="time">
                <div>文件时长：</div>
                <div>{{ item.estimatedTransmissionDuration }}</div>
              </div>
              <div class="size">
                <div>文件大小：</div>
                <div>{{ item.fileSize }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- <div class="right-content-bottom">
        <div
          class="link-btn"
          draggable="true"
          @click="showMakeLinkDialog"
          @dragstart="handleDragStart($event, '', '建链')"
        >
          建链
        </div>
        <div
          class="link-btn"
          draggable="true"
          @click="showUnpackLinkDialog"
          @dragstart="handleDragStart($event, '', '拆链')"
        >
          拆链
        </div>
      </div> -->
    </div>
    <el-dialog
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      :close-on-click-modal="true"
      :show-close="false"
      custom-class="empty-dialog"
      append-to-body
      width="50%"
      height="auto"
      top="5vh"
    >
      <TaskDefine
        :resourceData="resourceData"
        :testType="testType"
        @closeDialog="closeDialog"
        @sendData="defineTaskData"
      ></TaskDefine>
    </el-dialog>
    <el-dialog
      v-if="makeLinkVisible"
      :visible.sync="makeLinkVisible"
      :close-on-click-modal="true"
      :show-close="false"
      custom-class="empty-dialog"
      append-to-body
      width="50%"
      height="auto"
      top="15vh"
    >
      <MakeLink
        :offsetY="offsetY"
        @closeDialog="closeDialog"
        @sendData="defineTaskData"
      ></MakeLink>
    </el-dialog>
    <el-dialog
      v-if="unpackLinkVisible"
      :visible.sync="unpackLinkVisible"
      :close-on-click-modal="true"
      :show-close="false"
      custom-class="empty-dialog"
      append-to-body
      width="50%"
      height="auto"
      top="25vh"
    >
      <UnpackLink
        @closeDialog="closeDialog"
        @sendData="defineTaskData"
      ></UnpackLink>
    </el-dialog>
  </div>
</template>

<script>
import { getTaskByMonth, getDataSet, defineTask } from "@/api/taskArrangement";
import Highcharts from "highcharts/highstock";
import FullCalendar from "@fullcalendar/vue";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import listPlugin from "@fullcalendar/list";
import interactionPlugin from "@fullcalendar/interaction";
import GanttChart from "@/views/taskArrange/components/GanttChart.vue";
import TaskDefine from "@/views/taskArrange/components/TaskDefine.vue";
import MakeLink from "@/views/taskArrange/components/MakeLink.vue";
import UnpackLink from "@/views/taskArrange/components/UnpackLink.vue";
export default {
  name: "TestArrange",
  components: {
    FullCalendar, // make the <FullCalendar> tag available
    GanttChart,
    TaskDefine,
    MakeLink,
    UnpackLink,
  },
  data() {
    return {
      //上方日历数据
      loading: true,
      title: "",
      currentView: {},
      type: "dategrid",
      calendarOptions: {
        locale: "zh",
        timeZone: "local", // 使用本地时间，而不是UTC，否则会产生偏差
        plugins: [
          dayGridPlugin,
          timeGridPlugin,
          listPlugin,
          // resourceTimelinePlugin,
          interactionPlugin,
        ],
        buttonText: {
          // 设置按钮
          today: "今天",
          month: "月",
          week: "周",
          dayGrid: "天",
        },
        // 默认为那个视图（月：dayGridMonth，周：timeGridWeek，日：timeGridDay）
        initialView: "dayGridMonth", // 设置默认显示月，可选周、日
        resourceAreaWidth: 200,
        contentHeight: 420,
        slotMinWidth: 70,
        resourceOrder: "number",
        editable: true,
        dayMaxEvents: true, // allow "more" link when too many events
        eventDurationEditable: true, // 可以调整事件的时间
        selectable: true, // 日历格子可选择
        nowIndicator: true, // 现在的时间线显示
        eventDisplay: "block", // 争对全天的情况下，以块状显示
        headerToolbar: false, // 隐藏头部的导航栏
        selectMirror: false,
        displayEventEnd: true, // like 08:00 - 13:00
        eventTimeFormat: {
          // like '14:30:00'
          hour: "2-digit",
          minute: "2-digit",
          meridiem: false,
          hour12: false, // 设置时间为24小时
        },
        events: [],
        eventColor: "#378006",
        allDayText: "全天",
        dateClick: this.handleDateClick, //点击日程事件
        // eventClick: this.handleEventClick, //点击日历中的某一日程
        // select: this.handleDateSelect, // 监听用户选择的时间段，
        // eventDrop: this.handleEventDrop, //监听事件被拖动的操作
        // eventResize: this.handleEventResize, //监听事件调整大小的操作
        resourceAreaHeaderContent: "Rooms",
        resources: [
          {
            id: "111",
            title: "asas",
            number: 1,
          },
        ],
        schedulerLicenseKey: "GPL-My-Project-Is-Open-Source",
        resourceLabelContent(arg) {
          return {
            html: `<div>id: ${arg.resource.id}</div><div>title: ${arg.resource.title}</div>`,
          };
        },
        eventContent: function (arg) {
          // 解析标题中的 HTML 标签
          let data = arg.event.title;
          // 返回自定义的事件内容
          return {
            html: `<div>${data}</div>`,
          };
        },
        views: {
          customTimeLineWeek: {
            type: "resourceTimeline",
            duration: { weeks: 1 },
            slotDuration: { days: 1 },
            buttonText: "Custom Week",
            slotLabelFormat: {
              weekday: "long",
              // month: 'numeric',
              // day: 'numeric',
              omitCommas: true,
            },
          },
          customTimeLineMonth: {
            type: "resourceTimeline",
            duration: { month: 1 },
            slotLabelFormat: {
              // month: 'numeric',
              day: "numeric",
              // omitCommas: true,
            },
          },
          customGridWeek: {
            type: "timeGridWeek",
            dayHeaderFormat: {
              weekday: "long",
            },
            slotLabelFormat: {
              // 左侧时间格式
              hour: "2-digit",
              minute: "2-digit",
              meridiem: "lowercase",
              hour12: false, // false设置时间为24小时
            },
          },
        },
        // 切换视图调用的方法
        datesSet() {},
      },
      calendarApi: null,
      //右侧文件列表数据
      dataSetName: "",
      dataSetListData: {
        // 1：话音，2：数据，3：视频
        1: [
          {
            id: "1925789305948704769",
            dataSetName: "啵啵啵啵啵啵啵啵啵啵啵啵啵啵啵",
            dataSetType: "1",
            dataSetPath: "D:/opt/dataSet/1/嵌入式网路服务器技术.zip",
            fileName: "嵌入式网路服务器技术.zip",
            fileSize: "134.6 MB",
            remark: "哈哈哈哈哈哈哈哈哈哈哈哈",
            estimatedTransmissionDuration: 10, //预估传输时长
          },
        ],
        2: [],
        3: [],
      },
      // 任务定义弹窗
      dialogVisible: false,
      makeLinkVisible: false,
      unpackLinkVisible: false,
      // 点击日历表所触发的当天
      infoDateStr: "",
      resourceData: {},
      testType: null,
      dragTitle: "任务定义",
    };
  },
  computed: {},
  watch: {
    // 切换视图要调用接口获取事件
    "calendarApi.view.type"(newVal) {
      this.getCalendarData();
    },
  },
  methods: {
    // 获取日历信息
    getCalendarData() {
      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        //每次查询清空事件
        this.calendarOptions.events = [];
        // 查询当月测试任务信息
        getTaskByMonth(this.chineseDateStringToTimestamp(this.title))
          .then((res) => {
            let arr = [];
            const data = res.data;
            const code = res.code;
            if (code == 200) {
              // this.$message.success("当月测试任务信息成功");
            } else {
              this.$message.error("当月测试任务信息失败");
            }
            if (data != null) {
              data.forEach((item) => {
                // 暂时做没有cron的情况
                // 有cron用另一个时间字段,但是暂不开发

                let obj = {
                  title: `${item.startTime.slice(10)} ${item.taskName}`,
                  start: new Date(item.startTime).getTime(), // 事件开始日期为 7 月 17 日
                  end: new Date(item.endTime).getTime(), // 事件结束日期为 7 月 18 日（如果是全天事件，通常设置为第二天的开始）
                  color: "transparent", // 设置事件颜色
                };
                arr.push(obj);
              });
              this.calendarOptions.events = arr;
            }
          })
          .catch((err) => {
            console.log(err);
          });
      }, 200);
    },
    returnHourTimer(millisTimestamp) {
      // 创建一个新的 Date 对象，将时间戳传入构造函数
      const date = new Date(millisTimestamp);

      // 使用 Date 对象的 getHours() 和 getMinutes() 方法获取小时和分钟
      const hours = date.getHours();
      const minutes = date.getMinutes();
      let hourTime = hours + ":" + minutes;
      return hourTime;
    },
    chineseDateStringToTimestamp(chineseDateStr) {
      // 替换中文月份为英文
      let engDateStr = chineseDateStr.replace(/年/g, "-").replace(/月/g, "");

      // 确保月份是两位数
      let dateParts = engDateStr.split("-");
      if (dateParts[1].length === 1) {
        dateParts[1] = "0" + dateParts[1];
      }

      // 返回格式化后的日期字符串
      let formattedDate = dateParts.join("-");

      return formattedDate;
    },
    // 切换
    prev() {
      this.calendarApi.prev();
      this.title = this.calendarApi.view.title;
      this.getCalendarData();
    },
    next() {
      this.calendarApi.next();
      this.title = this.calendarApi.view.title;
      this.getCalendarData();
    },
    // 本月
    toNowMonth() {
      this.calendarApi.today();
      this.title = this.calendarApi.view.title;
      this.getCalendarData();
    },
    // 今天
    today(date, jsEvent, view) {
      this.calendarApi.today();
      this.title = this.calendarApi.view.title;
      this.getCalendarData();
    },
    // 月
    month() {
      this.calendarApi.changeView("dayGridMonth");
      this.calendarApi.today();
      this.title = this.calendarApi.view.title;
    },
    // 周
    week() {
      this.calendarApi.changeView("customGridWeek");
      this.calendarApi.today();
      this.title = this.calendarApi.view.title;
    },
    // 天
    day() {
      this.calendarApi.today();
      this.title = this.calendarApi.view.title;
    },
    getDataSetData(dataSetName) {
      getDataSet(dataSetName)
        .then((res) => {
          const code = res.code;
          const data = res.data;
          if (data != null) {
            this.dataSetListData = data;
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    searchList() {
      this.getDataSetData(this.dataSetName);
    },
    // 任务定义弹窗
    showDialog(item, testType) {
      this.testType = testType; //数据类型
      this.resourceData = item;
      this.dialogVisible = true;
    },
    // 任务定义弹窗
    showMakeLinkDialog() {
      this.makeLinkVisible = true;
    },
    // 任务定义弹窗
    showUnpackLinkDialog() {
      this.unpackLinkVisible = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.makeLinkVisible = false;
      this.unpackLinkVisible = false;
    },
    handleDateClick(info) {
      // 获取点击的当前日期  “2023-11-01”
      this.infoDateStr = info.dateStr;
    },

    // 任务定义，添加
    defineTaskData(taskDefineForm) {
      console.log("taskDefineForm", taskDefineForm);
      defineTask(taskDefineForm)
        .then((res) => {
          const code = res.code;
          if (code == 200) {
            this.$message.success("任务定义成功");
            this.closeDialog();
          } else {
            this.$message.error("任务定义失败");
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },

    //拖拽新增
    // 处理拖拽开始
    handleDragStart(e, testType, dragTitle,item) {
      this.testType = testType; //数据类型
      this.resourceData = item;
      this.dragTitle = dragTitle;
      console.log("@@@@@@@@@@@", dragTitle);
    },
    // 处理拖拽得时间
    handleDragTime(timestamp, offsetY) {
      console.log(timestamp);
      if (this.dragTitle == "建链") {
        this.makeLinkVisible = true;
      } else if (this.dragTitle == "拆链") {
        this.unpackLinkVisible = true;
      } else {
        this.dialogVisible = true;
      }

      // 创建一个新的 Date 对象来处理时间
      let date = new Date(timestamp);

      // 减去一个月
      date.setMonth(date.getMonth());

      // 获取调整后的时间戳
      let adjustedValue = date.getTime();

      // 获取 startTime
      let startTime = this.adjustToHalfHour(adjustedValue);
      this.resourceData.startTime = startTime;
    },

    // 将时间调整为最近的整点或半小时
    adjustToHalfHour(timestamp) {
      let date = new Date(timestamp);

      // 获取小时和分钟
      let hours = date.getHours();
      let minutes = date.getMinutes();

      // 如果分钟大于30，向上调整到半小时
      if (minutes >= 30) {
        date.setMinutes(30);
      } else {
        date.setMinutes(0);
      }

      // 设置秒和毫秒为0，确保是整点或半小时
      date.setSeconds(0);
      date.setMilliseconds(0);

      return Highcharts.dateFormat("%Y-%m-%d %H:%M:%S", date.getTime());
    },
  },
  created() {},
  mounted() {
    //获取日历数据
    setTimeout(() => {
      this.$nextTick(() => {
        this.calendarApi = this.$refs.fullCalendar.getApi();
        this.title = this.calendarApi.view.title;
        this.getCalendarData();
      });
    }, 1000);
    //获取文件资源列表
    this.getDataSetData();
  },
};
</script>

<style lang="scss" scoped>
.test-arrange {
  height: 100%;
  display: flex;
  color: #ffffff;
  .left {
    width: 82%;
    height: 100%;
    display: flex;
    flex-direction: column;
    .top {
      height: 60%;
      background: url("~@/assets/images/taskArrangement/calendar-border.png")
        no-repeat center center;
      background-size: 100% 100%;
      padding: 0 1.875rem;
      .fc-toolbar {
        width: 100%;
        margin: 0.625rem auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .fc-center {
          display: flex;
          align-items: center;
          .title {
            font-size: 1rem;
            padding: 0 1rem;
            font-weight: 700;
          }
        }
      }
    }
    .bottom {
      flex: 1;
    }
  }
  .right {
    flex: 1;
    height: 100%;
    background: url("~@/assets/images/taskArrangement/right-border.png")
      no-repeat center center;
    background-size: 100% 100%;
    margin-left: 1.25rem;
    padding: 1.25rem;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .right-tools {
      display: flex;
      justify-content: space-between;
    }
    .right-tools-search {
      display: flex;
      justify-content: space-between;
      margin: 0.75rem 0;
    }
    .right-content {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow-y: auto;
      .list-wrap {
        display: flex;
        // height: 33.333%;
        flex: 1;
        flex-direction: column;
        .title {
          display: flex;
          margin-top: 0.75rem;
          align-items: center;
          .title-name {
            color: #81b7eb;
            font-size: 1.125rem;
            letter-spacing: 0.125rem;
            font-weight: 600;
            margin: 0 0.625rem;
          }
          .title-icon {
            font-size: 0.75rem;
            color: #18bbff;
            transition: transform 0.3s ease; /* 添加过渡效果 */
          }
        }
        .content {
          flex: 1;
          .content-item {
            border: 0.125rem solid #7a9fd3;
            border-radius: 0.3125rem;
            background: linear-gradient(to bottom, #04357c, #042250);
            padding: 0.625rem;
            margin-top: 0.625rem;
            margin-right: 0.5rem;
            cursor: pointer;
            .text {
              color: #2fd5ff;
              font-size: 0.875rem;
              span {
                margin-left: 0.75rem;
              }
            }
            .time {
              display: flex;
              margin-top: 0.625rem;
              font-size: 0.8125rem;
            }
            .size {
              display: flex;
              margin-top: 0.625rem;
              font-size: 0.8125rem;
            }
          }
        }
      }
    }
    .right-content-bottom {
      height: 40px;
      display: flex;
      flex-direction: row;
      justify-content: center;
    }
  }
  /* 重写button样式 */
  .arrange-btn {
    color: #aedeff;
    border: 0.0625rem solid #4987e0;
    background: linear-gradient(to bottom, #0062a7, #00245f);
  }
  .arrange-btn:focus,
  .arrange-btn:hover {
    color: #00e4ff;
    border-color: #4987e0;
    background: linear-gradient(to bottom, #001a40, #003362);
  }
  /* 重写button样式 */
  .link-btn {
    cursor: pointer;
    color: #aedeff;
    border: 0.0625rem solid #4987e0;
    width: 120px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    margin: 0 10px 0 10px;
    background: linear-gradient(to bottom, #0062a7, #00245f);
  }
  .link-btn:focus,
  .link-btn:hover {
    color: #00e4ff;
    border-color: #4987e0;
    background: linear-gradient(to bottom, #001a40, #003362);
  }
  ::v-deep .el-input {
    width: 13.75rem;
  }
  /* 修改滚动条背景颜色 */
  ::-webkit-scrollbar {
    background-color: #04123b;
  }

  /* 修改滚动条的宽度 */
  ::-webkit-scrollbar {
    width: 0.375rem;
  }

  /* 修改滚动条轨道的背景颜色和边框 */
  ::-webkit-scrollbar-track {
    background-color: #04123b;
    border: 0.0625rem solid #416784;
  }

  /* 修改滚动条滑块的背景颜色和边框 */
  ::-webkit-scrollbar-thumb {
    background-color: #124385;
  }

  /* 修改滚动条滑块鼠标悬停时的背景颜色 */
  ::-webkit-scrollbar-thumb:hover {
    background-color: #0b60ce;
  }
}
</style>
<style></style>
